//
//  TDIdCardMessageGetC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/12.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDIdCardMessageGetC.h"


#import "TDYuDingCarSectionHeadView.h"
#import "TDIdCardGetMessageCell.h"
#import "TDIdCardMessageDesCell.h"

//#if !TARGET_IPHONE_SIMULATOR
//#import <IdcardQuality/IdcardQuality.h>
//#endif

#import <objc/runtime.h>
#import <AipOcrSdk/AipOcrSdk.h>
#import "NetWorkRequest.h"
#import "TDDriveCardMessageGetC.h"
#import <UIImageView+WebCache.h>
@interface TDIdCardMessageGetC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) NSInteger selIndex;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)UIImage *getFrontImage;//拍照获取到的照片-------
@property (nonatomic,strong)UIImage *getBackImage;//拍照获取到的照片-------

@property (nonatomic,copy)NSString *idNum;
@property (nonatomic,copy)NSString *idName;
@property (nonatomic,copy)NSString *idBirthdayDate;
@property (nonatomic,copy)NSString *idSex;
@property (nonatomic,copy)NSString *idAddress;
@property (nonatomic,copy)NSString *idMinZu;

@property (nonatomic,copy)NSString *idBackValidto;


@property (nonatomic,copy)NSString *idBackToTime;//有效期------
@end

@implementation TDIdCardMessageGetC{
    // 默认的识别成功的回调
    void (^_successHandler)(id);
    // 默认的识别失败的回调
    void (^_failHandler)(NSError *);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
   
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
}

- (IBAction)navBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupUI {
    //设置导航条
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.view.backgroundColor = [UIColor whiteColor];

    [self.tableView registerNib:[UINib nibWithNibName:@"TDIdCardGetMessageCell" bundle:nil] forCellReuseIdentifier:@"TDIdCardGetMessageCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDIdCardMessageDesCell" bundle:nil] forCellReuseIdentifier:@"TDIdCardMessageDesCellId"];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, -10)];
    }
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
}



#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath];
    return cell;
}



- (NSString *)getIdentifier:(NSIndexPath *)indexPath {

    NSString *iden = @"TDIdCardMessageDesCellId";
    if (indexPath.row == 0) {
        iden = @"TDIdCardMessageDesCellId";
    }else {
        iden = @"TDIdCardGetMessageCellId";
    }
    return iden;
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.row == 0) {
        TDIdCardMessageDesCell *idCardMessageDesCell = (TDIdCardMessageDesCell *)cell;
        
    }else{
        TDIdCardGetMessageCell *idCardGetMessageCell = (TDIdCardGetMessageCell *)cell;
        if (indexPath.row == 1) {
            if (_shareMineInfoModel.idfront) {
                NSString *imgStr = [NSString stringWithFormat:@"http://121.40.92.131/deepdriving/%@",_shareMineInfoModel.idfront];
                [idCardGetMessageCell.imv_idCard sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"idCard"]];
            }else {
                idCardGetMessageCell.imv_idCard.image = [UIImage imageNamed:@"idCard"];
            }
        }
        else {
            if (_shareMineInfoModel.idback) {
                 NSString *imgStr = [NSString stringWithFormat:@"http://121.40.92.131/deepdriving/%@",_shareMineInfoModel.idback];
                [idCardGetMessageCell.imv_idCard sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"idCard"]];
            }else {
                idCardGetMessageCell.imv_idCard.image = [UIImage imageNamed:@"idBack"];
            }
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TDYuDingCarSectionHeadView *headView = [TDYuDingCarSectionHeadView yuDingCarSectionHeadView];
    headView.lbe_title.text = @"驾驶人信息录入(1/3)";
    headView.frame = CGRectMake(0, 0, Width-40, 74);
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 74;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.selIndex = indexPath.row;
    if (indexPath.row == 1) {
       [self idcardOCROnlineFront];
    }else {
        [self idcardOCROnlineBack];
    }
    
}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    if (!_shareMineInfoModel) {
        [self getAllMessageNet];
    }
}
// MARK: - 本地数据
- (void)loadLocalData {
    [[AipOcrService shardService] authWithAK:@"GZPHYxmfWLbNCo4gwEF0khsR" andSK:@"kEtvLQ26bO0Cr9ljHxRYhlYUkoWjafSE"];
    //    CGFloat contentWidth = [UILabel calllHeightWithContent:title andLineNumber:0 andFont:[UIFont systemFontOfSize:14] andWidth:Width-50];
    __weak typeof(self) weakSelf = self;
    
    // 这是默认的识别成功的回调
    _successHandler = ^(id result){
        NSLog(@"%@", result);
        NSString *title = @"识别结果";
        NSMutableString *message = [NSMutableString string];
        
        if(result[@"words_result"]){
            if([result[@"words_result"] isKindOfClass:[NSDictionary class]]){
                [result[@"words_result"] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        [message appendFormat:@"%@: %@\n", key, obj[@"words"]];
                        NSString *keyStr = (NSString *)key;
                        if ([keyStr containsString:@"姓名"]) {
                             weakSelf.idName = [obj objectForKey:@"words"];
                        }else if ([keyStr containsString:@"出生"]) {
                            weakSelf.idBirthdayDate = [obj objectForKey:@"words"];
                        }else if ([keyStr containsString:@"公民身份号码"]) {
                            weakSelf.idNum = [obj objectForKey:@"words"];
                        }
                        else if ([keyStr containsString:@"性别"]) {
                            weakSelf.idSex = [obj objectForKey:@"words"];
                        }
                        else if ([keyStr containsString:@"住址"]) {
                            weakSelf.idAddress = [obj objectForKey:@"words"];
                        }
                        else if ([keyStr containsString:@"民族"]) {
                            weakSelf.idMinZu = [obj objectForKey:@"words"];
                        }else if ([keyStr containsString:@"失效日期"]) {
                            weakSelf.idMinZu = [obj objectForKey:@"words"];
                        }
                        
                    }else{
                        [message appendFormat:@"%@: %@\n", key, obj];
                    }
                    
                }];
            }else if([result[@"words_result"] isKindOfClass:[NSArray class]]){
                for(NSDictionary *obj in result[@"words_result"]){
                    if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        [message appendFormat:@"%@\n", obj[@"words"]];
                        
                    }else{
                        [message appendFormat:@"%@\n", obj];
                    }
                }
            }
            
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                UIImage *tmpImg = weakSelf.selIndex == 1 ? weakSelf.getFrontImage : weakSelf.getBackImage;
                [weakSelf uploadIDImg:tmpImg imagetype:nil];
            }];
        }else{
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            weakSelf.noticeText = @"身份信息识别失败,请重新识别";
            return;
        }
    };
    
    _failHandler = ^(NSError *error){
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        weakSelf.noticeText = @"身份信息识别失败,请重新识别";
        return;
    };
}


// MARK: - 上传图片数据
- (void)uploadIDImg:(UIImage *)image imagetype:(NSString *)imagetype{
    if (self.selIndex == 1) {
        imagetype = @"1";
    }else if (self.selIndex == 2) {
        imagetype = @"2";
    }
    [self progressHUDShowWithText:nil];
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *pictureDataString = [imageData base64EncodedStringWithOptions:0];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dic = @{
                          @"updateuserid":[HelpObject changeNull:[AppSetting shareAppSetting].memberid],
                          @"imagetype":imagetype,
                          @"imagedata":pictureDataString,
                          @"idno":[HelpObject changeNull:self.idNum]
                          };
    [NetWorkRequest postNetRequestData:UpLoadMemberMessage parmeters:dic response:^(NSDictionary *response) {
        [weakSelf progressHUDHideImmediately];
        if (response) {
            [AppSetting shareAppSetting].updatetime = response[@"data"][@"updatetime"];
            
            [weakSelf updateinfoMessage];
            [weakSelf getAllMessageNet];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"身份证照片上传失败" isSucceed:NO];
    }];
}


// MARK: - 上传个人信息-------
- (void)updateinfoMessage{
    [self progressHUDShowWithText:nil];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dic = @{
                          @"updateuserid":[HelpObject changeNull:[AppSetting shareAppSetting].memberid],
                          @"oldupdatetime":[HelpObject changeNull:[AppSetting shareAppSetting].updatetime],
                          @"idno":self.idNum,
                          @"membername":self.idName,
                          @"birthday":self.idBirthdayDate,
                          @"sex":self.idSex,
                          @"idvalidto":[HelpObject changeNull:self.idBackValidto]
                          };
    [NetWorkRequest postNetRequestData:UpdateMemberMessage parmeters:dic response:^(NSDictionary *response) {
        [weakSelf progressHUDHideImmediately];
        if (response) {
            [weakSelf progressHUDShowWithCompleteText:@"身份信息上传成功" isSucceed:YES];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"身份信息上传失败" isSucceed:NO];
    }];
}



// MARK: - 身份证识别
- (void)idcardOCROnlineFront {
    __weak typeof(self) weakSelf = self;
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeIdCardFont
                                 andImageHandler:^(UIImage *image) {
                                     weakSelf.getFrontImage = image;
                                     [[AipOcrService shardService] detectIdCardFrontFromImage:image
                                                                                  withOptions:nil
                                                                               successHandler:_successHandler
                                                                                  failHandler:_failHandler];
                                 }];
    
    
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (void)idcardOCROnlineBack{
    __weak typeof(self) weakSelf = self;

    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeIdCardBack
                                 andImageHandler:^(UIImage *image) {
                                     weakSelf.getBackImage = image;
                                     [[AipOcrService shardService] detectIdCardBackFromImage:image
                                                                                 withOptions:nil
                                                                              successHandler:_successHandler
                                                                                 failHandler:_failHandler];
                                 }];
    [self presentViewController:vc animated:YES completion:nil];
}


- (IBAction)nextBtnClick:(UIButton *)sender {
    
    // MARK: - 判断的时候记得先要判断网路数据----防止第一次认证一半出现的情况
    if ((self.getFrontImage && self.getBackImage) || (_shareMineInfoModel.idfront && _shareMineInfoModel.idback)) {
        TDDriveCardMessageGetC *driveCardMessageGetC = [[TDDriveCardMessageGetC alloc] init];
        driveCardMessageGetC.mineInfoModel = self.shareMineInfoModel;
        [self.navigationController pushViewController:driveCardMessageGetC animated:YES];
    }else {
        self.noticeText = @"请选验证身份证信息";
        return;
    }
    
}

- (void)getAllMessageNet {
    NSDictionary *dic = @{};
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:GetMemberMessage parmeters:dic response:^(NSDictionary *response) {
        if (response) {
            //保存数据---进行一系列的操作----------
            [AppSetting shareAppSetting].photo = response[@"data"][@"photo"];
            [AppSetting shareAppSetting].updatetime = response[@"data"][@"updatetime"];
            weakSelf.shareMineInfoModel = [TBRMineModel yy_modelWithJSON:response[@"data"]];
            [weakSelf.tableView reloadData];
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"获取个人信息失败" isSucceed:NO];
    }];
}


@end
